package com.wocai.jrt.orgadmin.message.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vteba.service.generic.impl.MyBatisServiceImpl;
import com.vteba.tx.jdbc.mybatis.spi.BaseDao;
import com.vteba.utils.id.ObjectId;
import com.wocai.jrt.orgadmin.appointment.dao.AppointmentDao;
import com.wocai.jrt.orgadmin.appointment.model.Appointment;
import com.wocai.jrt.orgadmin.customer.model.Customer;
import com.wocai.jrt.orgadmin.customer.service.spi.CustomerService;
import com.wocai.jrt.orgadmin.investor.model.Investor;
import com.wocai.jrt.orgadmin.investor.service.spi.InvestorService;
import com.wocai.jrt.orgadmin.message.dao.MessageLogDao;
import com.wocai.jrt.orgadmin.message.model.MessageLog;
import com.wocai.jrt.orgadmin.message.model.MessageLogBean;
import com.wocai.jrt.orgadmin.message.service.spi.MessageLogService;
import com.wocai.jrt.orgadmin.orders.model.Orders;
import com.wocai.jrt.orgadmin.orders.model.OrdersBean;
import com.wocai.jrt.orgadmin.orders.service.spi.OrdersService;
import com.wocai.jrt.orgadmin.product.model.InvestReport;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.model.ProductNet;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.utils.MessagePush;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 消息日志相关的service业务实现。
 * @author yinlei
 * @date 2015-8-19 16:27:42
 */
@Named
public class MessageLogServiceImpl extends MyBatisServiceImpl<MessageLog, MessageLogBean, String> implements MessageLogService {
	// 添加了方法后，记得改为private
	protected MessageLogDao messageLogDao;
	private static final Logger LOGGER = LoggerFactory.getLogger(MessageLogServiceImpl.class);
	@Inject 
	private ProductService productServiceImpl;
	@Inject 
	private CustomerService customerServiceImpl;
	@Inject 
	private InvestorService investorServiceImpl;
	@Inject 
	private AppointmentDao appoinementDao;
	@Inject 
	private OrdersService ordersServiceImpl;
	
	@Override
	@Inject
	public void setBaseDao(BaseDao<MessageLog, MessageLogBean, String> messageLogDao) {
		this.baseDao = messageLogDao;
		this.messageLogDao = (MessageLogDao) messageLogDao;
	}
	
	/**
	 * 获得消息日志List，Json格式。
	 * @param model 参数
	 * @return 消息日志List
	 */
	@Override
	public List<MessageLog> queryMyList(MessageLog model) {
		return messageLogDao.queryMyList(model);
	}
	
	/**
	 * 消息保存
	 * @param model 参数
	 * @return int
	 */
	@Override
	public int saveMessage(MessageLog model) {
		return messageLogDao.saveMessage(model);
	}
	
	/**
	 * 根据机构id获取员工id列表
	 * @param orgId
	 * @return
	 */
	@Override
	public List<String> getEmployeeList(String orgId) {
		return messageLogDao.getEmployeeList(orgId);
	}
	
	/**
	 * 消息日志批量保存
	 * @param List<MessageLog>
	 * @return int
	 */
	@Override
	public int msgLogInsertBatch(List<MessageLog> msgLogList) {
		return messageLogDao.msgLogInsertBatch(msgLogList);
	}
	
	/**
	 * 产品审核通过,向投后APP用户推送消息
	 */
	@Override
	public void productAuditMessage(String id){
		try {
			Product product = productServiceImpl.get(id);
			if(product != null){
				//获取该机构下所有的投后APP用户
				Investor investor = new Investor();
				String orgId = product.getOrgId();
				investor.setOrgId(orgId);
				List<Investor> invList = investorServiceImpl.pagedList(investor);
				Customer customer = new Customer();
				for (Investor inves : invList) {
					customer.setMobile(inves.getMobile());
					List<Customer> cusListTmp = customerServiceImpl.pagedList(customer);
					if(cusListTmp.size() == 1){
						Customer cus = cusListTmp.get(0);
						//向投后APP用户推送消息
						MessageLog message = new MessageLog();
						message.setId(ObjectId.get().toString());
						message.setSender("系统消息");
						message.setSource("机构后台");
						message.setType(3);
						message.setState(0);
						message.setSkipKey(id);
						message.setSkipType(4);
						message.setOrgId(orgId);
						message.setBusinessType(1);
						message.setCustomerId(cus.getId());
						Date date = new Date();
						message.setCreateTime(date);
						message.setSendTime(date);
						String msgEmp ="尊敬的"+cus.getName()+"，特为您推荐"+product.getBriefName()+"，点击查看详情";
						message.setMessage(msgEmp);
						//保存投后用户消息日志
		 				int res = this.save(message);
		 				if(res == 1){
		 					LOGGER.info("save message for customer at productAuditMessage success");
		 				}else{
		 					LOGGER.error("save message for customer at productAuditMessage error");
		 					return;
		 				}
		 				//向投后APP用户发送推送消息  (别名为投后用户id,组别为机构id) 
			    		MessagePush messageCusPush = new MessagePush(msgEmp,"系统消息",getUnReadNum(inves.getOrgId(),cus.getId()));
		     			messageCusPush.sendCusPushTag(inves.getOrgId(),cus.getId());
		     			LOGGER.info("send productAuditMessage message for customer [{}] result :"+cus.getName());
					}
				}
			}
		} catch (Exception e) {
			LOGGER.error("send productAuditMessage message for customer error :"+e.getMessage());
		}
		
	}
	
	/**
	 * 产品状态由即将上线变成募集中状态,向已预约该产品的投后APP用户推送消息
	 */
	@Override
	public void productStateChangeMessage(Product model) {
		//获取预约该产品的所有未处理的预约单
		try {
			Appointment appo = new Appointment();
			appo.setProductId(model.getId());
			appo.setOrgId(UserUtils.getOrgId());
			appo.setState(0);
			List<Appointment> appoList = appoinementDao.pagedList(appo);
			if(appoList.size() > 0 ){
				Customer customer = new Customer();
				for (Appointment a : appoList) {
					Investor investor = investorServiceImpl.get(a.getInvestorId());
					customer.setMobile(investor.getMobile());
					List<Customer> cusList = customerServiceImpl.pagedList(customer);
					if(cusList.size() == 1){
						Customer cus = cusList.get(0);
						//向投后APP用户推送消息
						MessageLog message = new MessageLog();
						message.setId(ObjectId.get().toString());
						message.setSender("系统消息");
						message.setSource("机构后台");
						message.setType(3);
						message.setState(0);
						message.setSkipKey(model.getId());
						message.setSkipType(4);
						message.setOrgId(UserUtils.getOrgId());
						message.setBusinessType(1);
						message.setCustomerId(cus.getId());
						Date date = new Date();
						message.setCreateTime(date);
						message.setSendTime(date);
						String msgEmp ="尊敬的"+cus.getName()+"，您预约的产品 "+model.getBriefName()+"，开始募集，点击查看详情。";
						message.setMessage(msgEmp);
						//保存投后用户消息日志
		 				int res = this.save(message);
		 				if(res == 1){
		 					LOGGER.info("save message for customer at productStateChangeMessage success");
		 				}else{
		 					LOGGER.error("save message for customer at productStateChangeMessage error");
		 					return;
		 				}
		 				//向投后APP用户发送推送消息  (别名为投后用户id,组别为机构id) 
		 				LOGGER.info("send productStateChangeMessage message for customer [{}] result :",cus.getId()+";"+investor.getOrgId());
			    		MessagePush messageCusPush = new MessagePush(msgEmp,"系统消息",getUnReadNum(investor.getOrgId(),cus.getId()));
		     			messageCusPush.sendCusPushTag(investor.getOrgId(),cus.getId());
					}
				}
			}
		} catch (Exception e) {
			LOGGER.info("send productStateChangeMessage message for customer error [{}]  :"+e.getMessage());
		}
		
	}
	
	/**
	 * 产品新增净值,向投后APP用户推送消息查看投后详情
	 */
	@Override
	public void productNetValueMessage(ProductNet model){
		try {
			//获取投后用户成功购买该产品的订单，订单状态为：6已完成 或者 7 即将到期
			OrdersBean ordersBean = new OrdersBean();
			List<Integer> stateList = new ArrayList<Integer>();
			stateList.add(6);
			stateList.add(7);
			ordersBean.createCriteria().andStateIn(stateList).andProductIdEqualTo(model.getProductId()).andOrgIdEqualTo(model.getOrgId());
			List<Orders> orders = ordersServiceImpl.pagedForList(ordersBean);
			Product p = productServiceImpl.get(model.getProductId());
			Customer customer = new Customer();
			LOGGER.info("push message for customer at productNetValueMessage task  begin");
			Set<String> invesSet = new HashSet<String>();
			for (Orders o : orders) {
				if(!o.getDeleted()){
					String investorId = o.getInvestorId();
					//该产品有多条订单的投资人不需要重复发送推送消息
					if(!invesSet.contains(investorId)){
						Investor investor = investorServiceImpl.get(o.getInvestorId());
						customer.setMobile(investor.getMobile());
						List<Customer> cusList = customerServiceImpl.pagedList(customer);
						if(cusList.size() == 1){
							Customer cus = cusList.get(0);
							//向投后APP用户推送消息
							MessageLog message = new MessageLog();
							message.setId(ObjectId.get().toString());
							message.setSender("系统消息");
							message.setSource("机构后台");
							message.setType(3);
							message.setState(0);
							message.setSkipKey(o.getOrderId());
							message.setSkipType(1);
							message.setOrgId(model.getOrgId());
							message.setBusinessType(2);
							message.setCustomerId(cus.getId());
							Date date = new Date();
							message.setCreateTime(date);
							message.setSendTime(date);
							String msgEmp ="尊敬的"+cus.getName()+"，您购买的"+p.getBriefName()+"发布了最新净值，点击查看详情";
							message.setMessage(msgEmp);
							//保存投后用户消息日志
			 				int res = this.save(message);
			 				if(res == 1){
			 					invesSet.add(investorId);
			 					LOGGER.info("save message for customer at productNetValueMessage success");
			 				}else{
			 					LOGGER.error("save message for customer at productNetValueMessage error");
			 					return;
			 				}
			 				//向投后APP用户发送推送消息  (别名为投后用户id,组别为机构id)
				    		MessagePush messageCusPush = new MessagePush(msgEmp,"系统消息",getUnReadNum(model.getOrgId(),cus.getId()));
			     			messageCusPush.sendCusPushTag(model.getOrgId(),cus.getId());
			     			LOGGER.info("send productNetValueMessage message for customer [{}] result :"+cus.getName());
						}
					}		
				}
			}
		} catch (Exception e) {
			LOGGER.error("send productNetValueMessage message for customer error ,[{}]:"+e.getMessage());
		}
	}
	
	/**
	 * 产品发布投后报告,向购买该产品的投后用户发送最新投后报告消息
	 */
	@Override
	public void productInvestReportMessage(InvestReport model) {
		//获取所有已完成订单
		try {
			OrdersBean ordersBean = new OrdersBean();
			List<Integer> stateList = new ArrayList<Integer>();
			stateList.add(6);
			stateList.add(7);
			ordersBean.createCriteria().andStateIn(stateList).andProductIdEqualTo(model.getProductId()).andOrgIdEqualTo(model.getOrgId());
			List<Orders> orders = ordersServiceImpl.pagedForList(ordersBean);
			String productId = model.getProductId();
			Product p =  productServiceImpl.get(productId);
			String orgId = model.getOrgId();
			Customer customer = new Customer();
			Set<String> invesSet = new HashSet<String>();
			if(!"".equals(productId)){
				for (Orders o : orders) {
					if(!o.getDeleted()){
						String investorId = o.getInvestorId();
						//该产品有多条订单的投资人不需要重复发送推送消息
						if(!invesSet.contains(investorId)){
							Investor investor = investorServiceImpl.get(investorId);
							customer.setMobile(investor.getMobile());
							List<Customer> cusList = customerServiceImpl.pagedList(customer);
							if(cusList.size() == 1){
								Customer cus = cusList.get(0);
								//向投后APP用户推送消息
								MessageLog message = new MessageLog();
								message.setId(ObjectId.get().toString());
								message.setSender("系统消息");
								message.setSource("机构后台");
								message.setType(3);
								message.setState(0);
								message.setSkipKey(o.getOrderId());
								message.setSkipType(1);
								message.setOrgId(model.getOrgId());
								message.setBusinessType(1);
								message.setCustomerId(cus.getId());
								Date date = new Date();
								message.setCreateTime(date);
								message.setSendTime(date);
								String msgEmp ="尊敬的"+cus.getName()+"，您购买的产品 "+p.getBriefName()+"，发布了最新投后报告，点击查看详情。";
								message.setMessage(msgEmp);
								//保存投后用户消息日志
				 				int res = this.save(message);
				 				if(res == 1){
				 					invesSet.add(investorId);
				 					LOGGER.info("save message for customer at productInvestReportMessage success");
				 				}else{
				 					LOGGER.error("save message for customer at productInvestReportMessage error");
				 					return;
				 				}
				 				//向投后APP用户发送推送消息  (别名为投后用户id,组别为机构id)
				 				String cusId = cus.getId();
				 				LOGGER.info("send productInvestReportMessage message for customer [{}] result :",orgId+";"+cusId);
					    		MessagePush messageCusPush = new MessagePush(msgEmp,"系统消息",getUnReadNum(orgId,cusId));
				     			messageCusPush.sendCusPushTag(orgId,cusId);
							}
						}
					}
				}	
			}
		} catch (Exception e) {
			LOGGER.info("send productInvestReportMessage message for customer  error ,[{}] :"+e.getMessage());
		}
	}
	
	/**
	 * 获取未读消息条数
	 * @param orgId
	 * @param customerId
	 * @return
	 */
	@Override
	public int getUnReadNum(String orgId,String customerId){
		int  systemNum = 0;//StringUtils.isBlank(oldPath)
		try {
			if(StringUtils.isAnyBlank(orgId,customerId)){
				LOGGER.error("get  UnRead MessageLog Num  param is null");
				return 0;
			}
			MessageLog msg = new MessageLog();
			msg.setCustomerId(customerId);
			msg.setOrgId(orgId);
			msg.setState(0);
			systemNum = this.pagedList(msg).size();
		} catch (Exception e) {
			LOGGER.error("get  UnRead MessageLog Num  error,[{}] :"+e.getMessage());
		}
		return systemNum;
	}
	
}
